<script setup lang="ts">
import { reactive, onMounted, onBeforeUnmount } from 'vue';
const props = defineProps({
    width: {
        type: Number,
        default: 1920
    },
    height: {
        type: Number,
        default: 1080
    },
    scaleByFatherCtn: {
        type: Boolean,
        default: false
    }
})
let style = reactive({
    width: props.width + 'px',
    height: props.height + 'px',
    transform: props.scaleByFatherCtn ? 'scale(1)' : 'scale(1) translate(-50%, -50%)'
})

onMounted(() => {
    style.transform = props.scaleByFatherCtn ? 'scale(1)' : 'scale(1) translate(-50%, -50%)'
    scale();
    window.onresize = debounce(scale);
})
onBeforeUnmount(() => {
    window.onresize = null;
})

function debounce(fn: any, timeout: number = 100) {
    let timer: null | number = null;
    // 声明this类型直接写在第一个形参上就可，不会影响其他参数的传递的
    return function (this: unknown, ...args: any[]) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
            timer = null;
        }, timeout);
    }
}
function scale() {
    const ctn = document.getElementsByClassName('scale-ctn')[0];
    const parentCtn: HTMLElement = ctn?.parentNode as HTMLElement;

    if (props.scaleByFatherCtn && parentCtn) {
        const scale = Math.min(parentCtn?.offsetWidth / props.width, parentCtn?.offsetHeight / props.height);
        // this.style.transform = `scale(${scale}) translate(-50%, -50%)`;
        style.transform = `scale(${parentCtn?.offsetWidth / props.width})`

        return;
    } else {
        // 网页可见区域宽高比window.innerWidth/Height 更合适
        // 因为window.innerWidth/Height在低分辨率下缩放会出现问题（body.client和windiw.inner不一致，windiw.inner会被里面的内容撑开导致缩放的不够小显示不全）
        console.log('log------------ document.body.clientWidth', document.body.clientWidth);
        console.log('log------------ document.body.clientHeight', document.body.clientHeight);
        console.log('log------------ window.innerWidth', window.innerWidth);
        console.log('log------------ window.innerHeight', window.innerHeight);
        const screenWidth = document.body.clientWidth;
        const screenHeight = document.body.clientHeight;
        const scale = Math.min(screenWidth / props.width, screenHeight / props.height);
        console.log('log------------ scale', scale);
        style.transform = `scale(${scale}) translate(-50%, -50%)`;
        // this.style.transform = `scale(${window.innerWidth / this.width}) translate(-50%, -50%)`;
        return;

    }

}
</script>

<template>
    <div id="scale-ctn" :class="{ 'scale-ctn': true, 'scale-ctn-absolute': !scaleByFatherCtn }" :style="style">
        <slot />
    </div>
</template>

<style scoped lang='less'>
.scale-ctn {
    transform-origin: 0 0;
    transition: 0.3s;
}

.scale-ctn-absolute {
    position: absolute;
    left: 50%;
    top: 50%;
}
</style>
